//
//  MainGameScene.m
//  Project 5
//
//  Created by Nguyen Tan Loc on 6/21/13.
//  Copyright (c) 2013 Nguyen Tan Loc. All rights reserved.
//

#import "MainGameScene.h"

@implementation MainGameScene
static MainGameScene *m_Instance = nil;

+(CCScene *) scene
{
	CCScene *scene = [CCScene node];
	MainGameScene *layer = [MainGameScene node];
	[scene addChild: layer z:0 tag:0];
	return scene;
}

+(MainGameScene *) getInstance
{
    return m_Instance;
}

-(id) init
{
	if(self = [super init])
    {
        m_Instance = self;
        
        [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:PLIST_INGAME textureFilename:IMAGE_INGAME];
        
        [[LevelManager shareLevelManager] setCurrentLevelt:0];
        [[LevelManager shareLevelManager] loadCurrentLevel];
        path = [[[LevelManager shareLevelManager] getPath] retain];
        [self addChild:path];
        
        Line *line = [[Line alloc] init];
        [line setPosition:ccp(120, 500)];
        [line setLength:100];
        [self addChild:line];
        
        self.touchEnabled = true;
        [self scheduleUpdate];
	}
    
	return self;
}

- (void) ccTouchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
    UITouch *touch = [touches anyObject];
    CGPoint touchLocation = [[CCDirector sharedDirector] convertTouchToGL:touch];
    
    [path processTouch:touch.phase position:touchLocation];
}

-(void) ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
//    CGPoint touchLocation = [touch locationInView: [touch view]];
    //    CGPoint prevLocation = [touch previousLocationInView: [touch view]];
    
    CGPoint touchLocation  = [[CCDirector sharedDirector] convertTouchToGL:touch];
    //    prevLocation = [[CCDirector sharedDirector] convertToGL: prevLocation];
    //    CGPoint diff = ccpSub(touchLocation, prevLocation);
    //    [b setPosition:ccp(b.position.x + diff.x, b.position.y + diff.y)];
    
    [path processTouch:touch.phase position:touchLocation];
};

-(void) ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint touchLocation = [[CCDirector sharedDirector] convertTouchToGL:touch];
    
    // fail if let finger out of screen
    
}


-(void) update:(ccTime)delta
{
    
}


-(void) dealloc
{
    [super dealloc];
    
    [[LevelManager shareLevelManager] removeData];
    
//    [[PhysicSystem sharedPhysicSystem] removeAllBody];
    CCLOG(@"MainGameScene dealloc");
}

@end
